package com.agileai.portal.controller.sso;

import java.util.List;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.MasterSubListHandler;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.core.Resource;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.SecurityAuthorizationConfig;
import com.agileai.portal.bizmoduler.sso.SSOApplicationManage;
import com.agileai.portal.bizmoduler.sso.UserSSOService;

public class SSOApplicationManageListHandler extends MasterSubListHandler{
	public SSOApplicationManageListHandler(){
		super();
		this.editHandlerClazz = SSOApplicationManageEditHandler.class;
		this.serviceId = buildServiceId(SSOApplicationManage.class);
	}
	protected void processPageAttributes(DataParam param) {
		setAttribute("appType",FormSelectFactory.create("SSO_APP_TYPE").addSelectedValue(param.get("appType")));
		initMappingItem("APP_TYPE",FormSelectFactory.create("SSO_APP_TYPE").getContent());
		initMappingItem("APP_GROUP",FormSelectFactory.create("SSO_APP_GROUP").getContent());
	}
	
	protected void initParameters(DataParam param) {
		initParamItem(param,"appName",""); initParamItem(param,"appType","");		
	}
	
	@PageAction
	public ViewRenderer isExistRelation(DataParam param){
		String responseText = "N";
		String appId = param.get("appId");
		UserSSOService userSSOService = this.lookupService(UserSSOService.class);
		if (userSSOService.isExistRelApplication(appId)){
			responseText = "existRelApplication";
		}
		String resourceId = appId;
		String resourceType = Resource.Type.Application;
		boolean isExistSecurityRelation = isExistSecurityRelation(resourceId, resourceType);
		if (isExistSecurityRelation){
			return new AjaxRenderer("existSecurityRelation");
		}
		return new AjaxRenderer(responseText);
	}
	
	private boolean isExistSecurityRelation(String resourceId,String resourceType){
		boolean result = false;
		SecurityAuthorizationConfig authorizationConfig = this.lookupService(SecurityAuthorizationConfig.class);
		List<DataRow> roleList = authorizationConfig.retrieveRoleList(resourceType, resourceId);
		if (roleList != null && roleList.size() > 0){
			result = true;
		}
		List<DataRow> userList = authorizationConfig.retrieveUserList(resourceType, resourceId);
		if (userList != null && userList.size() > 0){
			result = true;
		}
		List<DataRow> groupList = authorizationConfig.retrieveGroupList(resourceType, resourceId);
		if (groupList != null && groupList.size() > 0){
			result = true;
		}
		return result;
	}	
}
